﻿package com.projects.xenia;

import java.io.File;
import java.util.ArrayList;

import com.projects.xenia.documents_classes.Documents_Order;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.prompts_activities.Activity_OrderGoodsPrompt;
import com.projects.xenia.ref_classes.GoodsRefItem;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

 


public class MainGoodsImagesActivity extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
	
	private Context Ctx;	
	
	private ImageView mImageView;
	private Gallery mGallery;	 
	private TextView GoodsImageDescrLabel;
	private TextView GoodsImageAttribLabel;
	private TextView GoodsImageDocumentsLabel;
	private Drawable LImg;	
	private Documents_Order DocumentClass;
	
	private ArrayList<GoodsRefItem> GoodsGalleryRef= new ArrayList<GoodsRefItem> ();
	
	private ImageAdapter adap;
	
	private ImageButton imageButtonBuy;
	
	private void CopyGoodsRefToGalleryRef () {
		
		for (GoodsRefItem gi:MainGlobalModule.GoodsRef) {
			if (gi.isfolder!=1) {
				GoodsGalleryRef.add(gi);	
			}
		}
		
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	super.onCreate(savedInstanceState);
		    	
		Ctx = this;
		
        requestWindowFeature(Window.FEATURE_NO_TITLE);            
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);				
		
		setContentView(R.layout.goods_images_form);        
        
        mImageView = (ImageView)findViewById(R.id.fullsizeimage);        
        mImageView.setBackgroundColor(0xFFFFFFFF);
        mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        
        GoodsImageDescrLabel = (TextView)findViewById(R.id.GoodsImageDescrLabel);
    	GoodsImageAttribLabel = (TextView)findViewById(R.id.GoodsImageAttribLabel);
    	GoodsImageDocumentsLabel = (TextView)findViewById(R.id.GoodsImageDocumentsLabel);        
        
		Bundle DocExtra = getIntent().getExtras();
		
		CopyGoodsRefToGalleryRef ();
		
		adap = new ImageAdapter(this);
		
		mGallery = (Gallery) findViewById(R.id.gallery);
        mGallery.setAdapter(adap);
        mGallery.setOnItemSelectedListener(this);
        
        imageButtonBuy = (ImageButton)findViewById(R.id.imageButtonBuy);
        if (MainGlobalModule.DocumentClass != null) {
        	DocumentClass = (Documents_Order)MainGlobalModule.DocumentClass;
        	imageButtonBuy.setVisibility(View.VISIBLE);
        	imageButtonBuy.setOnClickListener(imageButtonBuy_Click);	
        }
        else
        {
        	imageButtonBuy.setVisibility(View.GONE);
        }
		
    }   
    
    private OnClickListener imageButtonBuy_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			
			if (MainGlobalModule.ExistsOffersByGoodsId ( DocumentClass.Head.id,gid.id)) {

				Toast.makeText(Ctx, "Товар использован в акции, используйте подбор по акции !", Toast.LENGTH_LONG).show();
				
			}
			else
			{
			
				GoodsRefItem gi = (GoodsRefItem)mGallery.getSelectedItem();				
				Intent OrderPrompt = new Intent ();				 
				OrderPrompt.setClass(Ctx,Activity_OrderGoodsPrompt.class);
				OrderPrompt.putExtra("GoodsRefPosition", gi.position);				 
				startActivityForResult(OrderPrompt, 0);
				
			}
		}
	};
    
    private GoodsRefItem gid;
    
    private void drawitem (int position) {
    	
    	gid = adap.getItem(position);        
        
    	GoodsImageDescrLabel.setText(gid.descr);
		GoodsImageAttribLabel.setText(String.format("ц:%.2f ост:%.2f (%s)",gid.price,gid.rest,gid.measure_base_descr));
		
		if (DocumentClass!=null) {
			double DocOrder = 0; 
			Documents_Order.DocLine DocLine = DocumentClass.DocLineCollection.get(gid.id);
			if (DocLine!=null){						
				DocOrder = DocLine.ordervalue;
				GoodsImageDocumentsLabel.setText(String.format("%.2f (%s)", DocOrder,gid.measure_base_descr));
			}
			else
			{
				GoodsImageDocumentsLabel.setText("");	
			}	
		}

    	new Thread(new Runnable() {
    		public void run() {
    			
        	    File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesPath,gid.id.trim()));
          	 	if (ImgPath.exists()==false) {
          	 		ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesThumbsPath,gid.id.trim()));
          	 	}
       		
          	 	if (ImgPath.exists()) {          	 		
          	 		LImg = Drawable.createFromPath(ImgPath.getAbsolutePath());
          	 		mImageView.setScaleType(ScaleType.FIT_CENTER);
          	 		mImageView.setAdjustViewBounds(true);
          	 		mImageView.post(new Runnable() 
        			{
                     public void run() 
                        {                    	 
                    	 mImageView.setImageDrawable(LImg);                    	 
                        }                         
        			});	
        	 	}
          	 	else
          	 	{
          	 		mImageView.post(new Runnable() 
        			{
                     public void run() 
                        {                    	 
                    	 mImageView.setImageResource(R.drawable.st_photos);                    	 
                        }                         
        			});
          	 	}
       		
        		
            }           
    	}).start();
    	
    }    
    
    public View makeView() {
    	    	
        ImageView i = new ImageView(this);       
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));        
        
        return i;
        
    }
        
    public class ImageAdapter extends BaseAdapter {
    	    	
    	public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
        	return GoodsGalleryRef.size ();
        }

        public GoodsRefItem getItem(int position) {        	
			return GoodsGalleryRef.get(position);            
        }

        public long getItemId(int position) {
            return position;
        }        
        
        public View getView(int position, View convertView, ViewGroup parent) {
        	        	       	
            ImageView i = new ImageView(mContext);
            
            GoodsRefItem gi = getItem(position);
            
            File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesThumbsPath,gi.id.trim()));
            
            if (ImgPath.exists()==false) {
            	ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesPath,gi.id.trim()));
            }
            
            if (ImgPath.exists()){
            	Drawable Img = Drawable.createFromPath(ImgPath.getAbsolutePath());               			                	
               	i.setImageDrawable(Img);
               	}
            else
            {
            	i.setImageResource(R.drawable.st_photos);
            }
            
        	i.setAdjustViewBounds(true);               			
           	i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
           	i.setAlpha(190);
           	i.setDrawingCacheEnabled(true);       
            
            return i;     
            
        }        
        
        private Context mContext;

    }
    
    @Override	
	public void onNothingSelected(AdapterView parent ) { 
		
    }
    
	@Override
	public void onItemSelected(AdapterView parent, View v, int position,long positionid) {
		
		drawitem(position);		
		
	}
	
	private void FinishActivity () {
		
		GoodsRefItem gi = (GoodsRefItem)mGallery.getSelectedItem();
		
		Intent DataIntent = new Intent ();
		setResult(RESULT_OK, DataIntent);
		DataIntent.putExtra("GoodsRefPosition", gi.position);		
		finish();
		
	}
    
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		if (keyCode==KeyEvent.KEYCODE_BACK) {
			FinishActivity();
		}
		
		return super.onKeyDown(keyCode, event);
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
	
		adap.notifyDataSetChanged();
	
		int _pos = data.getIntExtra("GoodsRefPosition",0);
		GoodsRefItem _gi = MainGlobalModule.GoodsRef.get(_pos);
		int _gos = 0;
		
		for (GoodsRefItem gi:GoodsGalleryRef) {
			if (gi.id.equals(_gi.id)) {
				mGallery.setSelection(_gos);		
			}
			_gos++;
		}
		 		    	
	};	
	
	
}
